import _ from 'underscore'
import dispatcher from 'lib/dispatcher'
import {Scope} from 'lib/scopeFactory'

import TimeStore from 'lib/stores/time-store'
import {coreApi,sortMap,parseToChart} from '../apis/core-util'
import {tracelistApi,createGridOrder,parseToPartGrid} from '../apis/tracelist'
export default class MainScope extends Scope {
  constructor(){
    super();
    this.$state = {
      chart0:{
        loading:true
      },
      chart1:{
        loading:true
      },
      grid:{
        loading:true,
        getOrder:createGridOrder('combination1',1),
        fetch:this.fetchGrid.bind(this)
      }
    }
    this.chart0Api = coreApi({
      limit:5,
      classify:'measurementname',
      viewKey:'js_error_count',
      urlName:'jsError'
    },TimeStore.getValue,function (){
      return {order:sortMap[this.viewKey]}
    });
    this.chart1Api = coreApi({
      limit:5,
      size:1,
      classify:'jserrtype',
      viewKey:'js_error_count',
      urlName:'jsError'
    },TimeStore.getValue,function (){
      return {order:sortMap[this.viewKey]}
    });
    this.gridApi = tracelistApi({
      urlName:'jsErrorList',
      classify:'jsurlmsg'
    },TimeStore.getValue,this.$state.grid.getOrder);
  }
  fetch(){
    var _this = this
    this.chart0Api.fetch().then(function(data,params){
      _this.$state.chart0 = {
        data:parseToChart(data,params)
      }
    },function(err){
      _this.$state.chart0 = {
        error:err
      }
    },function(params){
      _this.$state.chart0 = {
        loading:true,
        params:params
      }
      _this.emit()
    }).always(function(){
      _this.emit()
    })
    this.chart1Api.fetch().then(function(data,params){
      var parseData = parseToChart(data,params)
      parseData.series = [{
        name:'JS Errors',
        colorByPoint: true,
        data:parseData.series.map((s,i) => ({name:s.name,y:s.data[0].y,x:i,customData:s.data[0].customData}))
      }]
      _this.$state.chart1 = {
        data:parseData
      }
    },function(err){
      _this.$state.chart1 = {
        error:err
      }
    },function(params){
      _this.$state.chart1 = {
        loading:true,
        params:params
      }
      _this.emit()
    }).always(function(){
      _this.emit()
    })
    this.fetchGrid()
  }
  fetchGrid(){
    var _this = this
    this.gridApi.fetch().then(function gridHandle(data,params){
      _this.$state.grid = parseToPartGrid(data,params)
    },function(err){
      _this.$state.grid = {
        error:err
      }
    },function(params){
      _this.$state.grid = {
        loading:true,
        params:params
      }
      _this.emit()
    }).always(function(){
      _this.emit()
    })
  }
  $settime(payload){
    this.fetch()
  }
  $load(){
    this.fetch()
  }
}
